import {useEffect, useState} from 'react'
import {Toast} from 'antd-mobile'
import {reqGetHouseList} from '@/api'
import {getCurrentCity} from '@/utils/city'
import {useNavigate} from 'react-router-dom'
import SearchHeader from '@/components/SearchHeader'
import Sticky from '@/components/Sticky'
import Filter from './Filter'
import NoHouse from '@/components/NoHouse'
import List from 'react-virtualized/dist/commonjs/List'
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer'
import WindowScroller from 'react-virtualized/dist/commonjs/WindowScroller'
import InfiniteLoader from 'react-virtualized/dist/commonjs/InfiniteLoader'
import HouseItem from '@/components/HouseItem'
import {House} from '@/types'
import './index.less'

const List1: any = List
const AutoSizer1: any = AutoSizer
const WindowScroller1: any = WindowScroller
const InfiniteLoader1: any = InfiniteLoader

// 初始化默认值
let name = ''
let id = ''
// 初始化实例属性
let filters = {}

const HouseList = () => {
    // 列表数据
    const [list, setList] = useState<House[]>([])
    // 总条数
    const [count, setCount] = useState(0)
    // 数据是否加载中
    const [isLoading, setIsLoading] = useState(false)

    const nav = useNavigate()

    useEffect(() => {
        getCurrentCity().then((value1) => {
            const {label, value} = value1 as {label: string; value: string}
            name = label
            id = value
        })
        searchHouseList()
    }, [])

    // 用来获取房屋列表数据
    const searchHouseList = async () => {
        setIsLoading(true)
        Toast.show({icon: 'loading', content: '加载中…'})
        const res = await reqGetHouseList(id, filters, 1, 20)
        if (res.status === 200) {
            setList(res.body.list)
            setCount(res.body.count)
        }
        Toast.clear()
        if (count !== 0) {
            Toast.show({content: `共找到 ${count} 套房源`})
        }
        setIsLoading(false)
    }

    // 接收 Filter 组件中的筛选条件数据
    const onFilter = (value: Object) => {
        window.scroll(0, 0)
        filters = value
        searchHouseList()
    }

    // 渲染房屋列表项
    const renderHouseList = ({key, index, style}: any) => {
        // 根据索引号来获取当前这一行的房屋数据
        const house = list[index]

        // 判断 house 是否存在
        // 如果不存在，就渲染 loading 元素占位
        if (!house) {
            return (
                <div key={key} style={style}>
                    <p
                        style={{lineHeight: '120px', textAlign: 'center', height: '110px', backgroundColor: '#f6f5f6'}}
                    />
                </div>
            )
        }

        return (
            <HouseItem
                key={key}
                onClick={() => nav(`/detail/${house.houseCode}`)}
                // 注意：该组件中应该接收 style，然后给组件元素设置样式！！！
                style={style}
                item={house}
            />
        )
    }

    // 判断列表中的每一行是否加载完成
    const isRowLoaded = ({index}: any) => {
        return !!list[index]
    }

    // 用来获取更多房屋列表数据
    // 注意：该方法的返回值是一个 Promise 对象，并且，这个对象应该在数据加载完成时，来调用 resolve 让Promise对象的状态变为已完成。
    const loadMoreRows = ({startIndex, stopIndex}: any) => {
        return new Promise((resolve: any) => {
            reqGetHouseList(id, filters, startIndex, stopIndex).then((res: any) => {
                setList([...list, ...res.body.list])
                // 数据加载完成时，调用 resolve 即可
                resolve()
            })
        })
    }

    return (
        <div className='houseList'>
            {/* 顶部搜索导航 */}
            <div className='header'>
                <i className='iconfont icon-back' onClick={() => nav(-1)} />
                <SearchHeader cityName={name} className={'searchHeader'} />
            </div>

            {/* 条件筛选栏 */}
            <Sticky height={40}>
                <Filter onFilter={onFilter} />
            </Sticky>

            {/*渲染列表数据*/}
            {count === 0 && !isLoading ? (
                <NoHouse>没有找到房源，请您换个搜索条件吧~</NoHouse>
            ) : (
                <InfiniteLoader1 isRowLoaded={isRowLoaded} loadMoreRows={loadMoreRows} rowCount={count}>
                    {({onRowsRendered, registerChild}: any) => (
                        <WindowScroller1>
                            {({height, isScrolling, scrollTop}: any) => (
                                <AutoSizer1>
                                    {({width}: any) => (
                                        <List1
                                            onRowsRendered={onRowsRendered}
                                            ref={registerChild}
                                            autoHeight // 设置高度为 WindowScroller 最终渲染的列表高度
                                            width={width} // 视口的宽度
                                            height={height} // 视口的高度
                                            rowCount={count} // List列表项的行数
                                            rowHeight={120} // 每一行的高度
                                            rowRenderer={renderHouseList} // 渲染列表项中的每一行
                                            isScrolling={isScrolling}
                                            scrollTop={scrollTop}
                                        />
                                    )}
                                </AutoSizer1>
                            )}
                        </WindowScroller1>
                    )}
                </InfiniteLoader1>
            )}
        </div>
    )
}

export default HouseList
